import {
  loginByEmail,
  logout,
  getInfo,
  getUserType
} from 'api/login';
import {
  getToken,
  setToken,
  removeToken
} from 'utils/auth';
import {
  Base64
} from 'js-base64';
import {
  Message,
  MessageBox
} from 'element-ui';
import {
  queryIndustry,
  AU_State_list
} from "api/businessManagement/merchant/index";
import {
  queryBD_grade
} from "api/merchant/agent/index";


const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: '',
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    menus: undefined,
    elements: undefined,
    setting: {
      articlePlatform: []
    },
    userId: '',
    distributorId: '',
    companyId: '',
    currency: '',
    // password:'',
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction;
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting;
    },
    SET_STATUS: (state, status) => {
      state.status = status;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus;
    },
    SET_ELEMENTS: (state, elements) => {
      state.elements = elements;
    },
    LOGIN_SUCCESS: () => {
      console.log('login success')
    },
    LOGOUT_USER: state => {
      state.user = '';
    },

    SET_USERID: (state, userId) => {
      state.userId = userId;
    },
    SET_DISTRIBUTORID: (state, distributorId) => {
      state.distributorId = distributorId;
    },
    SET_COMPANYID: (state, companyId) => {
      state.companyId = companyId;
    },
    SET_CURRENCY: (state, currency) => {
      state.currency = currency;
    },
    SET_PASSWORD: (state, password) => {
      state.password = password;
    },
  },

  actions: {

    // 邮箱登录
    LoginByEmail({
      commit
    }, userInfo) {
      const phone = userInfo.phone.trim();
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      commit('SET_MENUS', undefined);
      commit('SET_ELEMENTS', undefined);
      removeToken();
      return new Promise((resolve, reject) => {

        //发送邮箱登录的请求
        loginByEmail(phone, userInfo.password).then(response => {
          if (response.code == '0') {
            const data = response;
            //base64 将返回的数据截取中间一段再解码
            const access = JSON.parse(Base64.decode(data.value.split('.')[1]));

            if(access.userType == 4 || access.userType == 7) {
              let errMsg;
              if(localStorage.getItem('locale') === 'zh_cn'){
                  errMsg = '账号不存在';
              }else if(localStorage.getItem('locale') === 'zh_tw'){
                  errMsg = '賬號不存在';
              }else{
                  errMsg = 'Account does not exist';
              }
              Message({ message: errMsg, type: 'error', duration: 5 * 1000 });
            } else {
              //获取token接口返回的数据解码之后打印出来
              //            console.log('token的信息');
              // console.log(access);
              sessionStorage.setItem("access-token", data.value);
              localStorage.setItem('access-userId', access.userId);

              localStorage.setItem("companyId", access.companyId);
              localStorage.setItem("userType", access.userType);

              //          commit('SET_USERID', access-userId);
              //          commit('SET_DISTRIBUTORID', access.distributorId);
              //          commit('SET_COMPANYID', access.companyId);
              getUserType(access.userId).then(res => {
                localStorage.setItem('userName', res.value.name);
                localStorage.setItem('whiteLabel', res.value.attr7);
                if (res.value.path) {
                  localStorage.setItem('userLoginImg', res.value.path);
                }
              });

              setToken(data.value);
              commit('SET_TOKEN', data.value);

              if (access.userType == 2) {
                localStorage.setItem("distributorId", access.distributorId);
                queryBD_grade(access.distributorId).then(res => {
                  localStorage.setItem('grade', res.value.grade);
                });
              } else {
                localStorage.removeItem('grade');
                localStorage.removeItem('distributorId');
              }

              if (access.userType == 8) {
                localStorage.setItem('salesmanId', access.salesmanId);
              } else {
                localStorage.removeItem('salesmanId');
              }

              if (access.userType == 10) {
                localStorage.setItem('firmId', access.firmId);
              } else {
                localStorage.removeItem('firmId');
              }

              if (access.userType == 1) {
                localStorage.setItem('merchantId', access.merchantId);
              } else {
                localStorage.removeItem('merchantId');
              }
            }
          } else if (response.code == '2' || response.code == '7') {
            let errMsg;
            if (localStorage.getItem('locale') === 'zh_cn') {
              errMsg = '账号不存在';
              //					    	 timeMsg = '密码错误，请重新登录';
            } else if (localStorage.getItem('locale') === 'zh_tw') {
              errMsg = '賬號不存在';
              //					    	 timeMsg = '密碼錯誤，請重新登入';
            } else {
              errMsg = 'Account does not exist';
              //					    	 timeMsg = 'Password incorrect, please re-enter';
            }
            Message({
              message: errMsg,
              type: 'error',
              duration: 5 * 1000
            })
          } else if (response.code == '11') {
            let timeMsg;
            if (localStorage.getItem('locale') === 'zh_cn') {
              timeMsg = '密码错误，请重新登录';
            } else if (localStorage.getItem('locale') === 'zh_tw') {
              timeMsg = '密碼錯誤，請重新登入';
            } else {
              timeMsg = 'Password incorrect, please re-enter';
            }
            Message({
              message: timeMsg,
              type: 'error',
              duration: 5 * 1000
            })
          } else if (response.code == '5') {
            let disabledMsg;
            if (localStorage.getItem('locale') === 'zh_cn') {
              disabledMsg = '该账号已被停用';
            } else if (localStorage.getItem('locale') === 'zh_tw') {
              disabledMsg = '該賬號已被停用';
            } else {
              disabledMsg = 'This account has been disabled';
            }
            Message({
              message: disabledMsg,
              type: 'error',
              duration: 5 * 1000
            })
          }
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        if (sessionStorage.getItem("access-token")) {

          // commit('SET_CURRENCY',localStorage.getItem('companyId') == '1' ? 'HK$ ' : 'A$ ' );

          queryIndustry(localStorage.getItem("locale") === "en" ? "1" : "0").then(res => {
            // console.log(res);
            localStorage.setItem('queryIndustryObj', JSON.stringify(res.value));

            // console.log(res.value);
            res.value.push({
              'industryName': localStorage.getItem("locale") === "en" ? 'Other' : '其它',
              'industryCode': '1111'
            });
            localStorage.setItem('queryIndustryObj_ad', JSON.stringify(res.value));
          })
          AU_State_list(localStorage.getItem("companyId"), localStorage.getItem("locale") === "en" ? "en" : "cn").then(res => {
            // console.log(res);
            localStorage.setItem('queryAU_State_list', JSON.stringify(res.value));
          })
          getInfo(sessionStorage.getItem("access-token")).then(response => {
            const data = response;
            //获取用户信息接口返回的数据
            //        console.log('用户信息接口返回的数据')
            //        console.log(data)
            commit('SET_ROLES', 'admin');
            commit('SET_NAME', data.value.username);
            commit('SET_AVATAR', 'http://git.oschina.net/uploads/42/547642_geek_qi.png?1499487420');
            commit('SET_INTRODUCTION', data.value.username);
            const menus = {};
            //        console.log(data.value.menus)
            for (let i = 0; i < data.value.menus.length; i++) {
              menus[data.value.menus[i].code] = true;
            }
            //					console.log(menus)
            commit('SET_MENUS', menus);
            const elements = {};
            for (let i = 0; i < data.value.elements.length; i++) {
              elements[data.value.elements[i].code] = true;
            }
            //        console.log(elements)
            commit('SET_ELEMENTS', elements);
            resolve(data);
          }).catch(error => {
            // alert(error);
            reject(error);
          });
        } else {
          return false;
        }

      });
    },

    // 第三方验证登录
    LoginByThirdparty({
      commit,
      state
    }, code) {
      return new Promise((resolve, reject) => {
        commit('SET_CODE', code);
        loginByThirdparty(state.status, state.email, state.code).then(response => {
          commit('SET_TOKEN', response.data.token);
          setToken(response.data.token);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        this.$router.push({
          path: '/dashboard'
        })
        //      logout(state.token).then(() => {
        //        commit('SET_TOKEN', '');
        //        commit('SET_ROLES', []);
        //        commit('SET_MENUS', undefined);
        //        commit('SET_ELEMENTS', undefined);
        //        removeToken();
        //        resolve();
        //      }).catch(error => {
        //        reject(error);
        //      });
      });
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('SET_MENUS', undefined);
        commit('SET_ELEMENTS', undefined);
        removeToken();
        resolve();
      });
    },

    // 动态修改权限
    ChangeRole({
      commit
    }, role) {
      return new Promise(resolve => {
        commit('SET_ROLES', [role]);
        commit('SET_TOKEN', role);
        setToken(role);
        resolve();
      })
    }
  }
};

export default user;
